from exts import db
from datetime import datetime
from flask_login import UserMixin
import hashlib


class UserModel(db.Model, UserMixin):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(20), nullable=False, unique=True)
    password = db.Column(db.String(200), nullable=False)
    email = db.Column(db.String(50), nullable=False, unique=True)
    first_name = db.Column(db.String(20))
    last_name = db.Column(db.String(20))
    address = db.Column(db.String(100))
    city = db.Column(db.String(50))
    country = db.Column(db.String(50))
    postal_code = db.Column(db.String(20))
    bio = db.Column(db.Text)
    avatar_url = db.Column(db.String(200))
    join_time = db.Column(db.DateTime, default=datetime.now)

    # Flask-Login 需要的属性
    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.id)

    @property
    def full_name(self):
        return f"{self.last_name or ''}{self.first_name or ''}".strip() or self.usernam

    # 用户模型添加生成头像
    @property
    def avatar_url(self):
        # 使用 Gravatar 生成头像（基于邮箱哈希）
        email_hash = hashlib.md5(self.email.strip().lower().encode()).hexdigest()
        return f"https://cravatar.cn/avatar/{email_hash}?d=identicon"



class EmailCaptchaModel(db.Model):
    __tablename__ = "email_captcha"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(100), nullable=False)
    captcha = db.Column(db.String(100), nullable=False)
    created_time = db.Column(db.DateTime, default=datetime.now)  # 记录创建时间

    # 使用过的验证码定期清理
    # userd = db.Column(db.Boolean, default=False)


class ImageCaptchaModel(db.Model):
    __tablename__ = "image_captcha"
    id = db.Column(db.String(36), primary_key=True)  # 使用UUID作为标识
    captcha_text = db.Column(db.String(10), nullable=False)  # 存储验证码文本
    created_time = db.Column(db.DateTime, default=datetime.now)


class UserBehavior(db.Model):
    __tablename__ = 'user_behavior'

    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, index=True)  # 添加索引
    item_id = db.Column(db.Integer, index=True)  # 添加索引
    category_id = db.Column(db.Integer, index=True)  # 添加索引
    behavior_type = db.Column(db.String(10), index=True)  # 添加索引
    timestamp = db.Column(db.DateTime, index=True)  # 添加索引

    # 复合索引
    __table_args__ = (
        db.Index('idx_user_item', 'user_id', 'item_id'),
        db.Index('idx_user_behavior', 'user_id', 'behavior_type'),
    )


class CleanedUserBehavior(db.Model):
    __tablename__ = 'cleaned_user_behavior'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, nullable=False)
    item_id = db.Column(db.Integer, nullable=False)
    category_id = db.Column(db.Integer, nullable=False)  # 新增字段
    behavior_type = db.Column(db.String(50), nullable=False)  # 行为类型（如 pv, buy, fav, cart）
    timestamp = db.Column(db.DateTime, nullable=False)  # 时间戳

    def __repr__(self):
        return f"<CleanedUserBehavior {self.user_id}, {self.item_id}, {self.category_id}, {self.behavior_type}, {self.timestamp}>"


class Log(db.Model):
    __tablename__ = 'log'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    timestamp = db.Column(db.DateTime, default=datetime.now)  # 日志时间
    user_id = db.Column(db.Integer, nullable=True)  # 用户ID，可以为空（未登录用户）
    behavior = db.Column(db.String(200), nullable=False)  # 操作行为
    details = db.Column(db.String(500), nullable=True)  # 操作详情

    def __repr__(self):
        return f"<Log {self.timestamp}, {self.user_id}, {self.behavior}, {self.details}>"
